#include "IAP.h"

void FLASH_WRITE_SUCCESS(uint8_t KEY)
{
    switch (KEY)
    {
    case 1:
        write_flash_key(FLASH_OPERATION_KEY_CODE_0);
        break;
    case 2:
        write_flash_key(FLASH_OPERATION_KEY_CODE_1);
        break;
    default:
        write_flash_key(FLASH_OPERATION_KEY_CODE_0);
        break;
    }
    NVIC_SystemReset();
}

void write_flash_key(uint32_t FLASH_OPERATION_KEY)
{
    FLASH_Unlock_Fast();
    FLASH_ErasePage_Fast(FLASH_KEY_ADDR);
    uint32_t Page_Address = FLASH_KEY_ADDR & 0xFFFFFF00;
    FLASH->CTLR |= CR_PAGE_PG;
    while (FLASH->STATR & SR_BSY)
        ;
    while (FLASH->STATR & SR_WR_BSY)
        ;
    *(uint32_t *)Page_Address = FLASH_OPERATION_KEY;
    while (FLASH->STATR & SR_WR_BSY)
        ;
    FLASH->CTLR |= CR_PG_STRT;
    while (FLASH->STATR & SR_BSY)
        ;
    FLASH->CTLR &= ~CR_PAGE_PG;
    FLASH_Lock_Fast();
}

uint32_t read_flash_key(void)
{
    return *((uint32_t *)FLASH_KEY_ADDR);
}